package com.example.safelib.fragment



import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer

import com.example.baselib.fragment.BaseFragment
import com.example.baselib.utils.TimeUtils
import com.example.safelib.LineChartMarkView
import com.example.safelib.R
import com.example.safelib.SafeViewModel
import com.example.safelib.bean.SafeLineCharList
import com.example.safelib.bean.SafeLineInfoBean
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.LimitLine
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import kotlinx.android.synthetic.main.fragment_safe_alarm_lc.*
import java.lang.Exception
import java.util.ArrayList


/**
 * A simple [Fragment] subclass.
 */
class SafeAlarmLCFragment : BaseFragment<SafeViewModel>() {


    override fun providerVMClass(): Class<SafeViewModel>? {
       return SafeViewModel::class.java
    }
    override fun contentLayout(): Int {
        return R.layout.fragment_safe_alarm_lc
    }

    override fun initView() {
        initChartView(first_rydw_chart)
    }
    override fun initData() {
        safe_alarm_lc_nickname.text= viewModel.getUnitInfo()["unitname"]
        val bundle: Bundle = arguments!!
        val map=HashMap<String,String>()
        map["sensornum"]=bundle.getString("sensornum")!!
        map["starttime"]= bundle.getString("starttime")!!
        map["endtime"]=  bundle.getString("endtime")!!
        viewModel.getLineChartData().observe(this, Observer {
                showLineChart(it)
                safe_alarm_lc_empty.visibility= View.INVISIBLE

        })
        viewModel.loadAlarmLine(map)
    }

    private fun showLineChart(charList: SafeLineCharList) {
        val senInfo = charList.lineInfo
        safe_alarm_lc_sen.text =senInfo.sensorname
        safe_alarm_lc_no.text=senInfo.sensornum
        safe_alarm_lc_local.text=senInfo.sensorplace
        val unit = if(senInfo.sensorunit ==null||senInfo.sensorunit=="")"" else "单位:" + senInfo.sensorunit
        // 获取的坐标数据集合
        val entries = ArrayList<Entry>()
        val mXData: ArrayList<String> = ArrayList()
        val iterator = charList.lineValue
        if (iterator.isNullOrEmpty()){
            return
        }
        for ((position, bean) in iterator.withIndex()) {
            entries.add(Entry(position.toFloat(), bean.realvalue.toFloat()))
            TimeUtils.chartTimeFormat(bean.datatime)?.let { mXData.add(it) }
        }
        setXAxis(first_rydw_chart,mXData)
        setYAxis(first_rydw_chart,senInfo)
        // 创建数据的包装类
        val lineDataSet = LineDataSet(entries, unit)
        lineDataSet.mode =
            if (senInfo.typename in setOf("开关量", "控制量", "多态量")) LineDataSet.Mode.STEPPED
            else LineDataSet.Mode.CUBIC_BEZIER
        initChartData(lineDataSet,first_rydw_chart)
        val mv = LineChartMarkView(activity!!.applicationContext, mXData, senInfo)
        mv.setChartView(first_rydw_chart)
        first_rydw_chart?.marker = mv
    }

    /**
     * @Description: [初始化折线图]
     * @Param: lineChart view
     * @Return:
     */
    private fun initChartView(lineChart: LineChart) {
//        lineChart.legend.isEnabled = false;// 不显示图例
        lineChart.legend.textSize = 14f
        lineChart.description.isEnabled = true
        lineChart.description.text = "时间"// 不显示描述
//        lineChart.setScaleEnabled(false);   // 取消缩放
        lineChart.setNoDataText("暂无数据")// 没有数据的时候默认显示的文字
        lineChart.setNoDataTextColor(Color.parseColor("#4472FA"))
        lineChart.setBorderColor(Color.parseColor("#4472FA"))
        lineChart.setTouchEnabled(true)
        lineChart.isDragEnabled = true
        // 如果x轴label文字比较大，可以设置边距
        lineChart.extraRightOffset = 25f
        lineChart.extraBottomOffset = 10f
        lineChart.extraTopOffset = 10f
        lineChart.setDrawBorders(false)//禁止绘制图表边框的线
        //设置是否可以触摸
        lineChart.setTouchEnabled(true)
    }

    /**
     * X轴相关
     */
    private fun setXAxis(lineChart: LineChart, mXData:List<String>) {
        // 设置x轴的数据
        val xAxis = lineChart.xAxis
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.textColor = Color.parseColor("#919191")
        xAxis.textSize = 10f
        // 设置x轴网格的颜色
        xAxis.gridColor = Color.parseColor("#919191")
        xAxis.granularity = 1.0f
        //如果设置为true，则在绘制时会避免“剪掉”在x轴上的图表或屏幕边缘的第一个和最后一个坐标轴标签项。
        // xAxis.setAvoidFirstLastClipping(true);
        // x轴最左多出空n个坐标
        xAxis.spaceMax = 10.0f
        // 让左侧x轴不从0点开始
        xAxis.spaceMin = 10.0f

// 获取到数据后，格式化x轴的数据
        xAxis.valueFormatter = IAxisValueFormatter { v, axisBase ->
            val index = v.toInt()
            // 只显示首尾日期
            if (index < 0 || index >= mXData.size) {//防止出现数组越界;
                ""
            } else {
                //  Log.e("index&&value", "value: "+ value +" index"+index+" time"+format_realtimes.get(index));
                mXData[index]
            }
        }
    }

    /**
     * Y轴相关
     */
    private fun setYAxis(lineChart: LineChart, senInfo: SafeLineInfoBean?) {
        // 不显示右侧Y轴
        val yAxisRight = lineChart.axisRight
        yAxisRight.isEnabled = false
        val yAxisLeft = lineChart.axisLeft
        // 强制显示Y轴6个坐标
//         yAxisLeft.setLabelCount(5, true)
        // 将y轴0点轴的颜色设置为透明
        yAxisLeft.zeroLineColor = Color.WHITE
        yAxisLeft.textColor = Color.parseColor("#919191")
        yAxisLeft.textSize = 10f
        //不显示最顶部的label
        yAxisRight.setDrawTopYLabelEntry(false)
        // 设置y轴网格的颜色
        yAxisLeft.gridColor = Color.parseColor("#919191")
//         yAxisLeft.setGranularity(0.5f);
        yAxisLeft.enableGridDashedLine(10f, 10f, 0f)
//        yAxisLeft.setAxisMaximum(0.0f);
        //Y方向文字的位置，在线外侧.(默认在外侧)
        yAxisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
        //设置label偏移量，正值向下，负值向上
        // yAxisLeft.setYOffset(-10f);
        yAxisLeft.spaceTop = 15f
        when (senInfo?.typename) {
            "开关量" -> {
                formatY(yAxisLeft, senInfo)
            }
            "控制量", "多态量" -> {
            }
            else -> {
                if (senInfo?.warningvalueup != null)
                    setHeightLimitLine(senInfo.warningvalueup.toFloat(), yAxisLeft, lineChart)
                if (senInfo?.warningvaluedown != null && senInfo.warningvaluedown < senInfo.warningvalueup)
                    setLowLimitLine(senInfo.warningvaluedown.toFloat(), yAxisLeft, lineChart)
            }
        }


    }

    private fun formatY(yAxisLeft: YAxis, senInfo: SafeLineInfoBean) {
        yAxisLeft.valueFormatter = IAxisValueFormatter { value, _ ->
            when (value) {
                0.0f -> senInfo.offdescribe
                1.0f -> senInfo.ondescribe
                else -> ""
            }
        }
    }

    /**
     * 设置高设置线
     */
    private fun setHeightLimitLine(height: Float, yAxis: YAxis, lineChart: LineChart) {
        val limitLine = LimitLine(height, "报警上限")
        limitLine.lineWidth = 1f
        limitLine.textSize = 10f
        limitLine.enableDashedLine(10f, 10f, 0f)
        limitLine.lineColor = Color.RED
        limitLine.textColor = Color.RED
        yAxis.addLimitLine(limitLine)
        lineChart.invalidate()
    }
    /**
     * 设置低设置线
     */
    private fun setLowLimitLine(low: Float, yAxis: YAxis, lineChart: LineChart) {
        val limitLine = LimitLine(low, "报警下限")
        limitLine.lineWidth = 1f
        limitLine.textSize = 10f
        limitLine.enableDashedLine(10f, 10f, 0f)
        limitLine.lineColor = Color.RED
        limitLine.textColor = Color.RED
        yAxis.addLimitLine(limitLine)
        lineChart.invalidate()
    }

    private fun initChartData(lineDataSet: LineDataSet, lineChart: LineChart) {

// 点击圆点不显示高亮
        lineDataSet.setDrawHighlightIndicators(false)
// 设置折线的颜色
        lineDataSet.color = Color.parseColor("#4472FA")
// 填充颜色(渐变色)
//        lineDataSet.setDrawFilled(true);
//        lineDataSet.setFillDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
//                new int[]{Color.parseColor("#ff"+color), Color.parseColor("#00"+color)}));
        lineDataSet.lineWidth = 2f
// 坐标不显示值
        lineDataSet.setDrawValues(false)
        lineDataSet.setDrawCircles(false)//在点上画圆 默认true
        val lineData = LineData()
        lineData.addDataSet(lineDataSet)
        lineChart.data = lineData
//        float ratio = (float) mXData.size() / (float) 12;
        //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
        lineChart.zoom(1f, 1f, 0f, 0f)
    }

    override fun requestError(it: Exception?) {
        safe_alarm_lc_empty.visibility= View.VISIBLE
        if (it?.message=="暂无数据"){
            safe_alarm_lc_empty.findViewById<TextView>(R.id.err_txt).text=it?.message
            safe_alarm_lc_empty.findViewById<TextView>(R.id.err_msg).visibility=View.INVISIBLE
//            safe_alarm_lc_empty.findViewById<ImageView>(R.id.err_img).visibility=View.INVISIBLE
        }else{
            super.requestError(it)
            safe_alarm_lc_empty.findViewById<TextView>(R.id.err_msg).text=it?.message
        }

        safe_alarm_lc_empty.findViewById<Button>(R.id.err_rest_btn).setOnClickListener {  viewModel.loadAlarmData() }
    }

}
